/**
 * @Title: MysqlConnectionUtil.java
 * @Package: com.xd100.function.util
 * @author: xiaoyu Mo (liujun)
 * @date: 2014-6-26 下午12:04:43
 */
package com.xd100.lzll.gm.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: MysqlConnectionUtil
 * @Description: 数据库连接工具类 说明:封装了 无参，有参，存储过程的调用
 * @author: xiaoyu Mo (liujun)
 * @date: 2014-6-26 下午12:04:43
 * 
 */
public class MysqlConnectionUtil {

	/**
	 * insert update delete SQL语句的执行的统一方法
	 * 
	 * @param sql
	 *            SQL语句
	 * @param params
	 *            参数数组，若没有参数则为null
	 * @return 受影响的行数
	 */
	public static int executeUpdate(String sql, Object[] params, Connection connection) throws Exception {
		// 受影响的行数
		int affectedLine = 0;
		PreparedStatement preparedStatement = null;
		try {
			// 调用SQL
			preparedStatement = connection.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject(i + 1, params[i]);
				}
			}
			// 执行
			affectedLine = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			throw new Exception(e.getMessage(),e);
		} finally {
			// 释放资源
			closeAll(connection, preparedStatement, null, null);
		}
		return affectedLine;
	}

	/**
	 * SQL 查询将查询结果直接放入ResultSet中
	 * 
	 * @param sql
	 *            SQL语句
	 * @param params
	 *            参数数组，若没有参数则为null
	 * @return 结果集
	 */
	private static ResultSet executeQueryRS(String sql, Object[] params,
			Connection connection) throws Exception {
		ResultSet resultSet = null;
		PreparedStatement preparedStatement = null;
		try {
			// 调用SQL
			preparedStatement = connection.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject(i + 1, params[i]);
				}
			}
			// 执行
			resultSet = preparedStatement.executeQuery();
		} catch (SQLException e) {
			throw new Exception(e.getMessage(),e);
		} 
		return resultSet;
	}

	/**
	 * SQL 查询将查询结果：一行一列
	 * 
	 * @param sql
	 *            SQL语句
	 * @param params
	 *            参数数组，若没有参数则为null
	 * @return 结果集
	 */
	public static Object executeQuerySingle(String sql, Object[] params,
			Connection connection) throws Exception {
		Object object = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			// 调用SQL
			preparedStatement = connection.prepareStatement(sql);
			// 参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject(i + 1, params[i]);
				}
			}
			// 执行
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				object = resultSet.getObject(1);
			}
		} catch (SQLException e) {
			throw new Exception(e.getMessage(),e);
		} finally {
			closeAll(connection, preparedStatement, resultSet, null);
		}
		return object;
	}

	/**
	 * 获取结果集，并将结果放在List中
	 * 
	 * @param sql
	 *            SQL语句
	 * @return List 结果集
	 */
	public static List<Object> excuteQuery(String sql, Object[] params,
			Connection connection) throws Exception {
		// 创建List
		List<Object> objList = new ArrayList<Object>();
		ResultSet resultSet = null;
		try {
			// 执行SQL获得结果集
			resultSet = executeQueryRS(sql, params, connection);
			// 创建ResultSetMetaData对象
			ResultSetMetaData rsmd = resultSet.getMetaData();
			// 获得结果集列数
			int columnCount = rsmd.getColumnCount();
			// 将ResultSet的结果保存到List中
			while (resultSet.next()) {
				Map<String, Object> map = new HashMap<String, Object>();
				for (int i = 1; i <= columnCount; i++) {
					map.put(rsmd.getColumnLabel(i), resultSet.getObject(i));
				}
				objList.add(map);
			}
		} catch (SQLException e) {
			throw new Exception(e.getMessage(),e);
		} finally {
			// 关闭所有资源
			closeAll(connection, null, resultSet, null);
		}
		return objList;
	}

	/**
	 * 存储过程带有一个输出参数的方法
	 * 
	 * @param sql
	 *            存储过程语句
	 * @param params
	 *            参数数组
	 * @param outParamPos
	 *            输出参数位置
	 * @param SqlType
	 *            输出参数类型
	 * @return 输出参数的值
	 */
	public static Object excuteQuery(String sql, Object[] params, int outParamPos,
			int SqlType, Connection connection) throws Exception {
		Object object = null;
		CallableStatement callableStatement = null;
		try {
			// 调用存储过程
			callableStatement = connection.prepareCall(sql);
			// 给参数赋值
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					callableStatement.setObject(i + 1, params[i]);
				}
			}
			// 注册输出参数
			callableStatement.registerOutParameter(outParamPos, SqlType);
			// 执行
			callableStatement.execute();
			// 得到输出参数
			object = callableStatement.getObject(outParamPos);
		} catch (SQLException e) {
			throw new Exception(e.getMessage(),e);
		} finally {
			// 释放资源
			closeAll(connection, null, null, callableStatement);
		}
		return object;
	}

	/**
	 * 关闭所有资源
	 */
	private static void closeAll(Connection connection,
			PreparedStatement preparedStatement, ResultSet resultSet,
			CallableStatement callableStatement) {
		// 关闭结果集对象
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		// 关闭PreparedStatement对象
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		// 关闭CallableStatement 对象
		if (callableStatement != null) {
			try {
				callableStatement.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		// 关闭Connection 对象
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
	}

}
